/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.continew.admin.asset.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.validation.ValidationUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.result.R;
import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;
import top.continew.admin.asset.model.req.ServiceImportRowReq;
import top.continew.admin.asset.model.resp.ServiceImportParseResp;
import top.continew.starter.core.exception.BusinessException;
import top.continew.starter.core.util.FileUploadUtils;
import top.continew.starter.core.validation.CheckUtils;
import top.continew.starter.extension.crud.model.query.PageQuery;
import top.continew.starter.extension.crud.model.resp.PageResp;
import top.continew.starter.extension.crud.service.BaseServiceImpl;
import top.continew.admin.asset.mapper.ServiceRecordsMapper;
import top.continew.admin.asset.model.entity.ServiceRecordsDO;
import top.continew.admin.asset.model.query.ServiceRecordsQuery;
import top.continew.admin.asset.model.req.ServiceRecordsReq;
import top.continew.admin.asset.model.resp.ServiceRecordsDetailResp;
import top.continew.admin.asset.model.resp.ServiceRecordsResp;
import top.continew.admin.asset.service.ServiceRecordsService;

import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务业务实现
 *
 * @author CharlieYan
 * @since 2025/06/25 17:35
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ServiceRecordsServiceImpl extends BaseServiceImpl<ServiceRecordsMapper, ServiceRecordsDO, ServiceRecordsResp, ServiceRecordsDetailResp, ServiceRecordsQuery, ServiceRecordsReq> implements ServiceRecordsService {

    @Override
    public PageResp<ServiceRecordsResp> page(ServiceRecordsQuery query, PageQuery pageQuery) {
        QueryWrapper<ServiceRecordsDO> queryWrapper = this.buildQueryWrapper(query);
        super.sort(queryWrapper, pageQuery);
        IPage<ServiceRecordsDetailResp> page = baseMapper.selectServiceRecordsPage(new Page<>(pageQuery
            .getPage(), pageQuery.getSize()), queryWrapper);
        PageResp<ServiceRecordsResp> pageResp = PageResp.build(page, super.getListClass());
        pageResp.getList().forEach(this::fill);
        return pageResp;
    }

    @Override
    protected QueryWrapper<ServiceRecordsDO> buildQueryWrapper(ServiceRecordsQuery query) {
        String fuzzy = query.getFuzzy();
        List<LocalDate> purchaseDate = query.getPurchaseDate();
        List<LocalDate> expireDate = query.getExpireDate();

        return new QueryWrapper<ServiceRecordsDO>().and(StrUtil.isNotBlank(fuzzy), q -> q.like("tt.name", fuzzy)
            .or()
            .like("tt.producer_name", fuzzy)

        )
            .between(CollUtil.isNotEmpty(purchaseDate), "tt.purchase_date", CollUtil.getFirst(purchaseDate), CollUtil
                .getLast(purchaseDate))
            .between(CollUtil.isNotEmpty(expireDate), "tt.expire_date", CollUtil.getFirst(expireDate), CollUtil
                .getLast(expireDate));

    }

    @Override
    public void downloadImportTemplate(HttpServletResponse response) throws IOException {
        try {
            FileUploadUtils.download(response, ResourceUtil.getStream("templates/import/service.xlsx"), "服务导入模板.xlsx");
        } catch (Exception e) {
            log.error("下载服务导入模板失败：{}", e.getMessage(), e);
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            response.setContentType(ContentType.JSON.toString());
            response.getWriter().write(JSONUtil.toJsonStr(R.fail("下载服务导入模板失败")));
        }
    }

    @Override
    public ServiceImportParseResp parseImport(MultipartFile file) {
        ServiceImportParseResp serviceImportParseResp = new ServiceImportParseResp();
        List<ServiceImportRowReq> importRowList;
        // 读取表格数据
        try {
            importRowList = EasyExcel.read(file.getInputStream())
                .head(ServiceImportRowReq.class)
                .sheet()
                .headRowNumber(1)
                .doReadSync();
        } catch (Exception e) {
            log.error("服务导入数据文件解析异常：{}", e.getMessage(), e);
            throw new BusinessException("数据文件解析异常");
        }
        // 总计行数
        serviceImportParseResp.setTotalRows(importRowList.size());
        CheckUtils.throwIfEmpty(importRowList, "数据文件格式不正确");
        // 有效行数：过滤无效数据
        List<ServiceImportRowReq> validRowList = this.filterImportData(importRowList);
        serviceImportParseResp.setValidRows(validRowList.size());
        CheckUtils.throwIfEmpty(validRowList, "数据文件格式不正确");

        //

        return null;
    }

    /**
     * 过滤无效的导入服务数据（批量导入不严格校验数据）
     *
     * @param importRowList 导入数据
     */
    private List<ServiceImportRowReq> filterImportData(List<ServiceImportRowReq> importRowList) {
        // 校验过滤
        List<ServiceImportRowReq> list = importRowList.stream()
            .filter(row -> ValidationUtil.validate(row).isEmpty())
            .toList();
        // 用户名去重
        return list.stream()
            .collect(Collectors.toMap(ServiceImportRowReq::getCode, service -> service, (existing,
                                                                                         replacement) -> existing))
            .values()
            .stream()
            .toList();
    }

}